<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" show-summary :summary-method="getSummaries" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="仓库名称" min-width="125">
        <template #default="{ row, $index }">
          <el-form-item
            :prop="`${$index}.warehouseId`"
            :rules="formRules.warehouseId"
            class="mb-0px!"
          >
            <el-select
              v-model="row.warehouseId"
              clearable
              filterable
              placeholder="请选择仓库"
              @change="onChangeWarehouse($event, row)"
              :filter-method="handleWarehouseFilter"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="180">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
              :filter-method="handleProductFilter"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="库存" min-width="100">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.stockCount" :formatter="erpCountFormatter" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="规格" min-width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            <el-input disabled v-model="row.productUnitName" />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- 新增价格列 -->
<!--      <el-table-column label="价格" min-width="150">-->
<!--        <template #default="{ row, $index }">-->
<!--          <el-form-item :prop="`${$index}.productPrice`" class="mb-0px!">-->
<!--            {{ getProductPrice(row.productId) }}-->
<!--          </el-form-item>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="数量" prop="count" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.count`" :rules="formRules.count" class="mb-0px!">
            <el-input-number
              v-model="row.count"
              controls-position="right"
              :min="1"
              :precision="0"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" round>+ 添加入库产品</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProductApi } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/acmWarehouse'
import { StockApi } from '@/api/acm/stock/stock'
import { erpCountFormatter, erpPriceInputFormatter, erpPriceMultiply, getSumValue } from '@/utils'
import { OnboardSupplyApi, OnboardSupplyVO } from '@/api/acm/onboardsupply'
import type { SummaryMethodProps } from 'element-plus' // 导入表格合计类型
import { ElMessage } from 'element-plus'

// 优化Props类型定义（支持undefined和合法数据）
const props = defineProps<{
  items?: any[]
  disabled?: boolean
}>()

// 表单基础状态
const formLoading = ref(false)
const formData = ref<any[]>([])
// 修复：表单Ref应为单个对象（Element Plus表单要求）
const formRef = ref<InstanceType<
  typeof import('element-plus/lib/components/form/src/form.vue')
> | null>(null)

// 表单校验规则（优化触发方式，适配下拉框）
const formRules = reactive({
  inId: [{ required: true, message: '入库编号不能为空', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'change' }], // 改为change触发
  productId: [{ required: true, message: '产品不能为空', trigger: 'change' }], // 改为change触发
  productPrice: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  count: [
    { required: true, message: '产品数量不能为空', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量不能小于1', trigger: 'blur' }
  ]
})

// -------------------------- 核心优化：仓库下拉框回显问题修复 --------------------------
const warehouseList = ref<WarehouseVO[]>([]) // 下拉显示用仓库列表
const warehouseAllList = ref<WarehouseVO[]>([]) // 完整仓库列表（缓存所有数据）

/** 1. 加载完整仓库列表（异步+错误处理） */
const loadAllWarehouses = async () => {
  if (warehouseAllList.value.length > 0) return warehouseAllList.value
  try {
    const data = await WarehouseApi.getWarehouseSimpleList()
    warehouseAllList.value = data || []
    return data
  } catch (error) {
    ElMessage.error('加载仓库列表失败，请重试')
    warehouseAllList.value = []
    return []
  }
}

/** 2. 确保已选仓库在下拉列表中（回显补全） */
const ensureSelectedWarehouseInList = async () => {
  await loadAllWarehouses()
  // 提取所有已选仓库ID（去空）
  const selectedWarehouseIds = formData.value.map((item) => item.warehouseId).filter(Boolean)
  selectedWarehouseIds.forEach((id) => {
    const isExist = warehouseList.value.some((item) => item.id === id)
    if (!isExist) {
      const warehouse = warehouseAllList.value.find((item) => item.id === id)
      if (warehouse) warehouseList.value.push(warehouse)
    }
  })
}

/** 3. 仓库过滤方法（合并已选+过滤结果） */
const handleWarehouseFilter = async (query?: string) => {
  await loadAllWarehouses()

  // 提取已选仓库（避免回显丢失）
  const selectedWarehouses = formData.value
    .map((item) => warehouseAllList.value.find((w) => w.id === item.warehouseId))
    .filter(Boolean)

  // 按查询条件过滤
  let filteredWarehouses: WarehouseVO[] = []
  if (!query) {
    filteredWarehouses = [...warehouseAllList.value].slice(0, 200) // 首屏200条性能优化
  } else {
    filteredWarehouses = warehouseAllList.value.filter((w) =>
      w.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并去重
  warehouseList.value = Array.from(
    new Map([...selectedWarehouses, ...filteredWarehouses].map((w) => [w.id, w])).values()
  )
  return warehouseList.value
}
// -----------------------------------------------------------------------------------

// -------------------------- 核心优化：产品下拉框回显问题修复 --------------------------
const productList = ref<OnboardSupplyVO[]>([]) // 下拉显示用产品列表
const productAllList = ref<OnboardSupplyVO[]>([]) // 完整产品列表（缓存所有数据）
const defaultWarehouse = ref<WarehouseVO | undefined>(undefined) // 默认仓库

/** 1. 加载完整产品列表（异步+错误处理） */
const loadAllProducts = async () => {
  if (productAllList.value.length > 0) return productAllList.value
  try {
    const data = await ProductApi.getJgpProductSimpleList()
    productAllList.value = data || []
    return data
  } catch (error) {
    ElMessage.error('加载产品列表失败，请重试')
    productAllList.value = []
    return []
  }
}

/** 2. 确保已选产品在下拉列表中（回显补全） */
const ensureSelectedProductInList = async () => {
  await loadAllProducts()
  // 提取所有已选产品ID（去空）
  const selectedProductIds = formData.value.map((item) => item.productId).filter(Boolean)
  selectedProductIds.forEach((id) => {
    const isExist = productList.value.some((item) => item.id === id)
    if (!isExist) {
      const product = productAllList.value.find((item) => item.id === id)
      if (product) productList.value.push(product)
    }
  })
}

/** 3. 产品过滤方法（合并已选+过滤结果） */
const handleProductFilter = async (query?: string) => {
  await loadAllProducts()

  // 提取已选产品（避免回显丢失）
  const selectedProducts = formData.value
    .map((item) => productAllList.value.find((p) => p.id === item.productId))
    .filter(Boolean)

  // 按查询条件过滤
  let filteredProducts: OnboardSupplyVO[] = []
  if (!query) {
    filteredProducts = [...productAllList.value].slice(0, 200) // 首屏200条性能优化
  } else {
    filteredProducts = productAllList.value.filter((p) =>
      p.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并去重
  productList.value = Array.from(
    new Map([...filteredProducts, ...selectedProducts].map((p) => [p.id, p])).values()
  )
  return productList.value
}

/** 产品价格回显（新增：对应价格列显示） */
const getProductPrice = (productId: any): string => {
  if (!productId) return ''
  const product = productAllList.value.find((item) => item.id === productId)
  return product ? erpPriceInputFormatter(product.productPrice) : ''
}
// -----------------------------------------------------------------------------------

/** 初始化设置入库项（优化：加载数据后补全回显） */
watch(
  () => props.items,
  async (val) => {
    formData.value = val || [] // 处理undefined情况
    // 补全已选仓库和产品的回显
    await Promise.all([ensureSelectedWarehouseInList(), ensureSelectedProductInList()])
    // 初始化已有数据的总价计算
    formData.value.forEach((item) => {
      const price = item.productPrice || 0
      const count = item.count || 1
      const taxPercent = item.taxPercent || 0
      item.totalProductPrice = erpPriceMultiply(price, count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, taxPercent / 100)
      item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
    })
  },
  { immediate: true, deep: true }
)

/** 监听表单数据变化（原有逻辑保留，优化容错） */
watch(
  () => formData.value,
  (val) => {
    if (!val || val.length === 0) return
    // 计算总价
    val.forEach((item) => {
      const productPrice = item.productPrice || 0
      const count = item.count || 0
      const taxPercent = item.taxPercent || 0

      item.totalProductPrice = erpPriceMultiply(productPrice, count)
      item.taxPrice = erpPriceMultiply(item.totalProductPrice, taxPercent / 100.0)
      item.totalPrice = item.totalProductPrice + (item.taxPrice || 0)
    })
  },
  { deep: true, flush: 'post' } // 确保DOM更新后执行，保证数据同步
)

/** 表格合计逻辑（修复类型定义，处理undefined值+价格列合计totalPrice） */
const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    // 价格列（index=5）回显totalPrice合计
    if (index === 5) {
      const totalPriceSum = getSumValue(data.map((item) => Number(item.totalPrice || 0)))
      sums[index] = erpPriceInputFormatter(totalPriceSum)
    }
    // 只对数值型字段进行合计
    else if (
      ['count', 'totalProductPrice', 'taxPrice', 'totalPrice'].includes(column.property as string)
    ) {
      // 处理数据中的undefined，转为0后求和
      const sum = getSumValue(data.map((item) => Number(item[column.property] || 0)))
      sums[index] =
        column.property === 'count' ? erpCountFormatter(sum) : erpPriceInputFormatter(sum)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

/** 新增产品行（原有逻辑保留，优化默认值） */
const handleAdd = () => {
  const row = {
    id: undefined,
    warehouseId: defaultWarehouse.value?.id, // 关联默认仓库
    productId: undefined,
    productUnitName: undefined, // 产品规格
    productPrice: 0, // 初始化价格为0，避免计算异常
    stockCount: undefined,
    count: 1, // 默认数量1
    totalProductPrice: 0,
    taxPercent: 0, // 默认税率0
    taxPrice: 0,
    totalPrice: 0,
    remark: undefined
  }
  formData.value.push(row)
  // 新增后补全仓库/产品回显（防止默认仓库不在显示列表）
  ensureSelectedWarehouseInList()
}

/** 删除产品行（优化边界校验） */
const handleDelete = (index: number) => {
  if (index < 0 || index >= formData.value.length) return // 边界校验
  formData.value.splice(index, 1)
}

/** 处理仓库变更（优化：从完整列表获取数据） */
const onChangeWarehouse = async (warehouseId: any, row: any) => {
  await loadAllWarehouses()
  // 加载库存（仓库变更时重新计算库存）
  await setStockCount(row)
}

/** 处理产品变更（优化：触发响应式更新+计算总价） */
const onChangeProduct = async (productId: any, row: any) => {
  await loadAllProducts()
  const product = productAllList.value.find((item) => item.id === productId)
  const index = formData.value.findIndex((item) => item === row)
  if (product && index !== -1) {
    // 用splice触发响应式更新
    formData.value.splice(index, 1, {
      ...row,
      productId,
      productUnitName: product.standardName || '', // 产品规格
      productPrice: product.productPrice || 0, // 产品单价
      // 计算总价相关字段
      totalProductPrice: erpPriceMultiply(product.productPrice || 0, row.count || 1),
      taxPrice: erpPriceMultiply(
        erpPriceMultiply(product.productPrice || 0, row.count || 1),
        (row.taxPercent || 0) / 100
      ),
      totalPrice:
        erpPriceMultiply(product.productPrice || 0, row.count || 1) +
        erpPriceMultiply(
          erpPriceMultiply(product.productPrice || 0, row.count || 1),
          (row.taxPercent || 0) / 100
        )
    })
  } else if (index !== -1) {
    // 产品不存在时清空相关字段
    formData.value.splice(index, 1, {
      ...row,
      productUnitName: '',
      productPrice: 0,
      totalProductPrice: 0,
      taxPrice: 0,
      totalPrice: 0
    })
  }
  // 加载库存（产品变更时重新计算库存）
  await setStockCount(formData.value[index])
}

/** 加载库存（优化错误处理） */
const setStockCount = async (row: any) => {
  if (!row.productId || !row.warehouseId) {
    row.stockCount = undefined
    return
  }
  try {
    const stock = await StockApi.getStock2(row.productId, row.warehouseId)
    row.stockCount = stock ? stock.count : 0
  } catch (error) {
    ElMessage.warning('获取库存失败，默认显示0')
    row.stockCount = 0
  }
}

/** 表单校验（修复：适配单个表单Ref） */
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}
defineExpose({ validate })

/** 初始化（优化：并行加载数据，确保完整性） */
onMounted(async () => {
  formLoading.value = true
  try {
    // 并行加载完整仓库和产品列表（提升加载速度）
    const [warehouses, products] = await Promise.all([loadAllWarehouses(), loadAllProducts()])

    // 初始化显示列表（首屏200条）
    await Promise.all([handleWarehouseFilter(), handleProductFilter()])

    // 设置默认仓库
    defaultWarehouse.value = warehouses.find((item) => item.defaultStatus)

    // 初始化表单数据
    formData.value = props.items || []
    // 补全已选数据回显
    await Promise.all([ensureSelectedWarehouseInList(), ensureSelectedProductInList()])

    // 若初始无数据，默认添加一行
    if (formData.value.length === 0) {
      handleAdd()
    }
  } catch (error) {
    ElMessage.error('初始化失败，请刷新重试')
    console.error('初始化错误:', error)
  } finally {
    formLoading.value = false
  }
})
</script>
